export default (dragEndFn?: Function) => {
  let startX = 0;
  let startY = 0;
  let offsetX = 0;
  let offsetY = 0;
  let dragDiv: HTMLElement | void;
  function mousedownHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    // 鼠标按下时记录鼠标位置和元素初始位置
    startX = e.clientX;
    startY = e.clientY;
    offsetX = this.offsetLeft;
    offsetY = this.offsetTop;
    document.addEventListener('mousemove', mousemoveHandler);
    document.addEventListener('mouseup', mouseupHandler);
  }
  function mousemoveHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    // 鼠标移动时更新元素位置
    const deltaX = e.clientX - startX;
    const deltaY = e.clientY - startY;
    dragDiv && (dragDiv.style.left = offsetX + deltaX + 'px');
    dragDiv && (dragDiv.style.top = offsetY + deltaY + 'px');
  }

  function mouseupHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    document.removeEventListener('mousemove', mousemoveHandler);
    document.removeEventListener('mouseup', mouseupHandler);
    if (dragEndFn) {
      dragEndFn();
    }
  }
  const setDragAble = (dragDivDom: HTMLElement) => {
    dragDiv = dragDivDom;
    dragDiv.addEventListener('mousedown', mousedownHandler);
  };
  const removeDragAble = (dragDivDom: HTMLElement) => {
    dragDivDom.removeEventListener('mousedown', mousedownHandler);
  };
  return {
    setDragAble,
    removeDragAble
  };
};
